package com.zkingsoft.actions.dingding;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dingtalk.open.client.api.model.corp.CorpUserBaseInfo;
import com.dingtalk.open.client.api.model.corp.CorpUserDetail;
import com.zkingsoft.constance.Dictionary;
import com.zkingsoft.dingding.auth.AuthHelper;
import com.zkingsoft.dingding.user.UserHelper;
import com.zkingsoft.model.Bug;
import com.zkingsoft.model.Changes;
import com.zkingsoft.model.ExperienceLevel;
import com.zkingsoft.model.Function;
import com.zkingsoft.model.RolePwoer;
import com.zkingsoft.model.Task;
import com.zkingsoft.model.Users;
import com.zkingsoft.model.WorkLog;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.plugin.util.EncrypUtil;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.pojo.UserPwoer;
import com.zkingsoft.services.BugService;
import com.zkingsoft.services.ChangesService;
import com.zkingsoft.services.CompanyService;
import com.zkingsoft.services.ExperienceLevelService;
import com.zkingsoft.services.FunctionService;
import com.zkingsoft.services.RolePwoerService;
import com.zkingsoft.services.TaskService;
import com.zkingsoft.services.UsersService;
import com.zkingsoft.services.WorkLogService;
import com.zkingsoft.thread.SendOaMsgsThread;

@Controller
@RequestMapping(value = "dd/dingding")
public class DingDingController {
	
	@Resource
	private UsersService usersService;
	@Resource
	private CompanyService companyService;
	@Resource
	private FunctionService functionService;
	@Resource
	private RolePwoerService rolePwoerService;
	@Resource
	private TaskService taskService;
	@Resource
	private BugService bugService;
	@Resource
	private ExperienceLevelService exLevelService;
	@Resource
	private ChangesService changesService;
	
	@Autowired
	private WorkLogService workLogService;
	
	/**
	 * @Description:获取钉钉userId
	 * @author:dingchuan
	 * @param accessToken
	 * @param code
	 * @return
	 * @throws Exception
	 * 返回类型 AjaxResult
	 * @date 2016年11月27日
	 */
	@RequestMapping(value = "/getDdUserInfo")
	public @ResponseBody AjaxResult getDdUserInfo(String code){
		try {
			String accessToken = AuthHelper.getAccessToken();
			CorpUserBaseInfo userBaseInfo = UserHelper.getUserInfo(accessToken, code);
			if(userBaseInfo != null){
				return new AjaxResult(AjaxResult.STATUS_OK,null,"获取钉钉端用户信息成功",(List<?>) userBaseInfo,1);
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AjaxResult(AjaxResult.STATUS_ERR,null,"获取钉钉端用户信息失败");
		
	}
	
	
	/**
	 * @Description:检查是否绑定账号
	 * @author:dingchuan
	 * @param accessToken
	 * @param code
	 * @return
	 * @throws Exception
	 * 返回类型 AjaxResult
	 * @date 2016年11月27日
	 */
	@RequestMapping(value = "/checkIsBinding")
	public @ResponseBody AjaxResult checkIsBinding(String code,HttpServletRequest request){
		Users users = new Users();
		try {
			String accessToken = AuthHelper.getAccessToken();
			CorpUserBaseInfo userBaseInfo = UserHelper.getUserInfo(accessToken, code);//用户基本信息
			CorpUserDetail user = (CorpUserDetail)UserHelper.getUser(accessToken, userBaseInfo.getUserid());
			if(userBaseInfo == null){
				return new AjaxResult(AjaxResult.STATUS_ERR,null,"获取钉钉端用户信息失败");
			}
			String ddUserId = userBaseInfo.getUserid();
			users.setValidateCode(ddUserId);
			List<Users> userList = usersService.findByModel(users);
			if(userList !=null && userList.size() == 1){
				AjaxResult ajxaResult = new AjaxResult();
				Map<Object, Object> map = ajxaResult.getMapInfo();
				map.put("ddUserId", ddUserId);
				ajxaResult.setStatus("canLogin");
				ajxaResult.setInfo("直接登录");
				return ajxaResult;
			}else{	
				AjaxResult ajxaResult = new AjaxResult();
				Map<Object, Object> map = ajxaResult.getMapInfo();
				map.put("ddUserId", ddUserId);
				ajxaResult.setStatus(AjaxResult.STATUS_OK);
				ajxaResult.setInfo("还没有绑定账号");
				return ajxaResult;
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AjaxResult(AjaxResult.STATUS_ERR,null,"已经绑定账号");
	}
	
	/**
	 * @Description:免登录
	 * @author:dingchuan
	 * @param code
	 * @return
	 * 返回类型 String
	 * @date 2016年11月28日
	 */
	@RequestMapping(value = "/autoLogin")
	public @ResponseBody AjaxResult autoLogin(String ddUserId, HttpServletRequest request){
		Users user = new Users();
		user.setValidateCode(ddUserId);
		List<Users> userList = usersService.findByModel(user);
		if(userList != null && userList.size() == 1 ){
			AjaxResult ajaxResult = typeHandeler(userList.get(0), request);
			return ajaxResult;
		}
		return new AjaxResult(AjaxResult.STATUS_ERR,null,"自动登录失败");
	}
	
	
	
	/**
	 * @Description:绑定用户账号
	 * @author:dingchuan
	 * @param users
	 * @return
	 * 返回类型 AjaxResult
	 * @date 2016年11月27日
	 */
	@RequestMapping(value = "/bindingGeekUser")
	public @ResponseBody AjaxResult bindingGeekUser(String account,String password,
			String ddUserId, HttpServletRequest request){
		Users user = new Users();
		user.setAccount(account);
		try {
			user.setPassword(EncrypUtil.getMD5(password));
		} catch (Exception e) {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "绑定失败,请重试");
		}
		List<Users> userList = usersService.findByModel(user);
		if (userList != null && userList.size() > 0) {
			//进行绑定
			user = userList.get(0);
			user.setValidateCode(ddUserId);//绑定钉钉userId
			int result = usersService.modify(user);
			if(result > 0){
				return typeHandeler(user, request);
			}else{
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "绑定失败,请重试");
			}
		}else{
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号或者密码错误");
		}	
	}
	
	
	/**
	 * 根据用户类型不同进行不同的处理
	 * 
	 * @param user
	 * @param request
	 * @return
	 */
	private AjaxResult typeHandeler(Users user, HttpServletRequest request) {
		ExperienceLevel exLevel = new ExperienceLevel();
	    exLevel.setLevelName(user.getGrade());
	    List<ExperienceLevel> exLevelList = exLevelService.findByModel(exLevel); 
	    user.setImage(exLevelList.get(0).getImage());		
		// 如果不是超级管理员
		if (!user.getUserType().equals(Dictionary.USER_TYPE_SUPER)) {
			WebUtil.getSession().setAttribute("company", companyService.findById(user.getCompanyId()));
		}

		// 开发人员
		if (user.getUserType().equals(Dictionary.USER_TYPE_DEVELOPER)) {
			request.getSession().setAttribute("user", user);
			return new AjaxResult(AjaxResult.STATUS_OK, "developer/redirect/index", null);
		} else if (user.getUserType().equals(Dictionary.USER_TYPE_SUPER)) {
			// 超级管理员
			request.getSession().setAttribute("user", user);
			return new AjaxResult(AjaxResult.STATUS_OK, "super/redirect/index", null);
			// 企业管理员
		} else if (user.getUserType().equals(Dictionary.USER_TYPE_ADMIN)) {
			request.getSession().setAttribute("user", user);
			// 获取用户所有的权限信息
			UserPwoer userPwoer = getUserPwoer(user);
			request.getSession().setAttribute("userPwoer", userPwoer);
			return new AjaxResult(AjaxResult.STATUS_OK, "admin/redirect/index", null);
			// 企业用户
		} else if (user.getUserType().equals(Dictionary.USER_TYPE_EMPLOYEE)) {
			request.getSession().setAttribute("user", user);
			// 获取用户所有的权限信息
			UserPwoer userPwoer = getUserPwoer(user);
			request.getSession().setAttribute("userPwoer", userPwoer);
			return new AjaxResult(AjaxResult.STATUS_OK, "admin/redirect/index", null);
			// 普通用户
		} else if (user.getUserType().equals(Dictionary.USER_TYPE_EMPLOYEE)) {
			request.getSession().setAttribute("user", user);
			return new AjaxResult(AjaxResult.STATUS_OK, "admin/redirect/index", null);
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, "common/redirect/login", "什么鬼！");
	}
	
	
	/**
	 * 获取用户操作权限
	 * 
	 * @param user
	 * @return
	 */
	private UserPwoer getUserPwoer(Users user) {
		UserPwoer userPwoer = new UserPwoer();
		// 公司用户 **过滤个人权限
		if (user.getUserType().equals(Dictionary.USER_TYPE_EMPLOYEE)) {
			RolePwoer rpQuery = new RolePwoer();
			rpQuery.setRoleId(user.getRoleId());
			List<RolePwoer> rolePwoerList = rolePwoerService.findByModel(rpQuery);
			Map<Long, RolePwoer> powers = new HashMap<>();
			for (RolePwoer rolePwoer : rolePwoerList) {
				powers.put(rolePwoer.getFunctionId(), rolePwoer);
			}
			userPwoer.setPowers(powers);
			List<Function> functions = new ArrayList<>();
			List<Function> topFunction = functionService.findRoleFunctionByGrade(user.getRoleId(), 1);
			for (Function function : topFunction) {
				function.setChildenFunctions(
						functionService.selectRoleFunctionByParent(user.getRoleId(), function.getId()));
				functions.add(function);
			}
			userPwoer.setFunctions(functions);

			// 公司管理员的权限等于公司权限 ** 过滤公司权限
		} else if (user.getUserType().equals(Dictionary.USER_TYPE_ADMIN)) {
			List<Function> functions = new ArrayList<>();
			Function fnQuery = new Function();
			fnQuery.setGrade(1);
			List<Function> topFunctions = functionService.filterFunction(functionService.findByModel(fnQuery),
					user.getCompany());
			for (Function topFunction : topFunctions) {
				fnQuery.setGrade(null);
				fnQuery.setParentId(topFunction.getId());
				topFunction.setChildenFunctions(
						functionService.filterFunction(functionService.findByModel(fnQuery), user.getCompany()));
				functions.add(topFunction);
			}
			userPwoer.setFunctions(functions);
			Map<Long, RolePwoer> powers = new HashMap<>();
			for (Function function : functions) {
				for (Function childenfunction : function.getChildenFunctions()) {
					RolePwoer rolePwoer = new RolePwoer();
					rolePwoer.setBtns(childenfunction.getBtns());
					powers.put(childenfunction.getId(), rolePwoer);
				}
			}
			userPwoer.setPowers(powers);
		}
		return userPwoer;
	}
	
	
	@RequestMapping(value="/findTaskById")
	public @ResponseBody AjaxResult findTaskById(Long id){
		Task task = taskService.findById(id);
		if(task!=null){
			List<Task> list = new ArrayList<>();
			list.add(task);
			return new AjaxResult(AjaxResult.STATUS_OK, null, "查询成功", list, list.size());
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "查询失败");
	}
	/**
	 * 
	 * @Description:根据id查bug
	 * @author:chenxianzi
	 * @param 
	 * @return AjaxResult
	 * @date 2016年12月15日
	 */
	@RequestMapping(value="/findBugById")
	public @ResponseBody AjaxResult findBugById(Long id){
		Bug bug = bugService.findById(id);
		if(bug!=null){
			List<Bug> list = new ArrayList<>();
			list.add(bug);
			return new AjaxResult(AjaxResult.STATUS_OK, null, "查询成功", list, list.size());
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "查询失败");
	}
	
	@RequestMapping(value="/findChangesById")
	public @ResponseBody AjaxResult findChangesById(Long id){
		Changes changes = changesService.findUserCodeByChangesId(id);
		if(changes!=null){
			return new AjaxResult(AjaxResult.STATUS_OK, null, "查询成功", Arrays.asList(changes), 1);
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "查询失败");
	}
	
	
	@RequestMapping(value="/findNoFinishTaskByUserId")
	public @ResponseBody AjaxResult findNoFinishTaskByUserId(Task task){
		Long userId = task.getUserId();
		List<Task> tasks = taskService.findTaskNoFinish(userId); 
		if(tasks!=null){
			return new AjaxResult(AjaxResult.STATUS_OK, null, "查询成功", tasks, tasks.size());
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "查询失败");
	}
	
	
	/**
	 * @Description:改变任务状态为已开始
	 * @author:dingchuan
	 * @return 返回类型 AjaxResult
	 * @date 2016年11月13日
	 */
	@RequestMapping(value = "/changeTaskStart")
	public @ResponseBody AjaxResult changeTaskStart(Task task) {
		Task checkTask = taskService.findById(task.getId());
		String status = checkTask.getStatus();
		if (Dictionary.TASK_STATUS_NO_START.equals(status)) {
			checkTask.setStatus(Dictionary.TASK_STATUS_YES_START);// 已开始
			int result = taskService.modify(checkTask);
			if (result > 0) {
				//发送oa消息
				List<Long> taskIds = new ArrayList<>();
				taskIds.add(task.getId());
				SendOaMsgsThread send = new SendOaMsgsThread(taskService, taskIds,
						Dictionary.BG_COLOR_START, Dictionary.TITLE_START, true, null);
				new Thread(send).start();			
				return new AjaxResult(AjaxResult.STATUS_OK, null, "任务开始成功");
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "任务开始失败");
			}
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, "", "状态不是未开始不能开始！");
	}

	@RequestMapping(value = "/addAssess")
	public String addAssess(Long id) {
		Task task = taskService.findById(id);
		WebUtil.getRequest().setAttribute("obj", task);
		return "common/task-assess-form";
	}
	
	/**
	 * @Description:评价
	 * @author:dingchuan
	 * @param task
	 * @return
	 * 返回类型 AjaxResult
	 * @date 2016年12月21日
	 */
	@RequestMapping(value = "/modifyAssess")
	public @ResponseBody AjaxResult modifyAssess(Task task) {
		Task modifyTask = taskService.findById(task.getId());
		if (modifyTask != null) {
			modifyTask.setAssess(task.getAssess());
			int result = taskService.modify(modifyTask);
			if(result>0){
				SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
				//创建oa消息
				Map<String, String> oaMap1 = new HashMap<String, String>();
				oaMap1.put("key", "任务状态");
				oaMap1.put("value", Dictionary.TITLE_ASSESS);
				Map<String, String> oaMap2 = new HashMap<String, String>();
				oaMap2.put("key", "被评价人");
				oaMap2.put("value", modifyTask.getAssignName());
				Map<String, String> oaMap3 = new HashMap<String, String>();
				oaMap3.put("key", "评价人");
				oaMap3.put("value", modifyTask.getCreateName());
				Map<String, String> oaMap4 = new HashMap<String, String>();
				oaMap4.put("key", "评价时间");
				oaMap4.put("value", sdf.format(new Date()));
				Map<String, String> oaMap5 = new HashMap<String, String>();
				oaMap5.put("key", "评价内容");
				oaMap5.put("value", modifyTask.getAssess());
				List<Map<String, String>> oaList = new ArrayList<Map<String, String>>();
				oaList.add(oaMap1);
				oaList.add(oaMap2);
				oaList.add(oaMap3);
				oaList.add(oaMap4);
				oaList.add(oaMap5);
				//发送OA消息
				SendOaMsgsThread send = new SendOaMsgsThread(taskService, Arrays.asList(modifyTask.getId()),
						Dictionary.BG_COLOR_ASSESS, Dictionary.TITLE_ASSESS, false,oaList);
				new Thread(send).start();
				return new AjaxResult(AjaxResult.STATUS_OK, null, "评价成功");
			}		
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "评价失败");
	}
	
	  @RequestMapping("/show")
	    public @ResponseBody AjaxResult show(long workLogId) {
	    	AjaxResult result = new AjaxResult();
	    	WorkLog work = workLogService.selectWorkLogId(workLogId);
	    	List<WorkLog> list = new  ArrayList<>();
	    	list.add(work);
	    	result.setRows(list);
	    	result.setStatus(AjaxResult.STATUS_OK);
	    	return result;
	    }
	  
	  @RequestMapping("/showLogTime")
	  public @ResponseBody AjaxResult showLogTime(long workLogId) {
		  AjaxResult result = new AjaxResult();
		  Users user = usersService.findById(workLogId);
		  SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		  String[] dates = {df.format(DateUtils.nextDate((Date) user.getLogSendTime())),df.format(DateUtils.nextNDate((Date) user.getLogSendTime(),2)),df.format(DateUtils.nextNDate((Date) user.getLogSendTime(),3))};
		  user.setAccount(dates[0]);
		  user.setAddress(dates[1]);
		  user.setAccountStatus(dates[2]);
		  List<Users> list = new  ArrayList<>();
		  list.add(user);
		  result.setRows(list);
		  result.setStatus(AjaxResult.STATUS_OK);
		  return result;
	  }
}
